package org.jeecg.modules.clue.factory.carPlate;


import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.util.UUIDGenerator;
import org.jeecg.modules.clue.entity.ClueRecordTask;
import org.jeecg.modules.clue.entity.ClueTaskQueryLog;
import org.jeecg.modules.clue.enums.ChannelInviteStatus;
import org.jeecg.modules.clue.enums.ClueQueryStatus;
import org.jeecg.modules.clue.enums.TaskPushStatus;
import org.jeecg.modules.clue.enums.XlbClueStatus;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.Optional;

/**
 * 小喇叭平台
 */
@Component("XLBCarPlate")
@Slf4j
public class XLBCarPlateService implements CarPlateService {

    private static String PUSH_URL = "https://clue.xlbnb.com/clue-collect/car-seller/v1/push/common";
    private static String QUERY_URL = "https://clue.xlbnb.com/clue-collect/car-seller/v1/status/common";

    public static String generateMD5Signature(String param) {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        byte[] bytes = param.getBytes(StandardCharsets.UTF_8);
        byte[] digest = md.digest(bytes);
        // 将摘要转换为16进制字符串
        StringBuilder hexString = new StringBuilder();
        for (byte b : digest) {
            String hex = Integer.toHexString(0xFF & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }

    @Override
    public void push(ClueRecordTask recordTask) {
        log.info("XLBCarPlate 开始推送={}", JSON.toJSON(recordTask));
        String key = recordTask.getTpUsername();
        long time = System.currentTimeMillis() / 1000;
        JSONObject clueJson = new JSONObject();



        clueJson.put("bd_clue_id", UUIDGenerator.generate());
        clueJson.put("owner_name", recordTask.getDelayPushTime());
        clueJson.put("city", recordTask.getCity());
        clueJson.put("phone", recordTask.getPhone());

        String brandName = recordTask.getBrandName();
        String seriesName = recordTask.getSeriesName();
        String specName = recordTask.getSpecName();
        Date firstRegTime = recordTask.getFirstRegTime();

        clueJson.put("car_brand", Optional.ofNullable(brandName).orElse(""));
        clueJson.put("car_series", Optional.ofNullable(seriesName).orElse(""));
        clueJson.put("car_model", Optional.ofNullable(specName).orElse(""));
        if (null != firstRegTime) {
            clueJson.put("licensed_date", DateUtil.format(firstRegTime, "yyyy-MM-dd"));
        }


        String clue = clueJson.toJSONString();
        String sign = generateMD5Signature(String.format("%s%s%s", key, time, clue));

        JSONObject bodyMap = new JSONObject();
        bodyMap.put("key", key);
        bodyMap.put("time", time);
        bodyMap.put("sign", sign);
        bodyMap.put("clue", clue);

        String requestUrl = PUSH_URL;
        HttpRequest request = HttpUtil.createPost(requestUrl);
        request.contentType("application/json");
        request.body(bodyMap.toJSONString());
        log.info("requestUrl {}", requestUrl);
        log.info("requestBody {}", bodyMap);
        HttpResponse execute = request.execute();
        String body = execute.body();
        log.info("XLBCarPlate 推送结果={}", body);

        JSONObject resultBody = JSONObject.parseObject(body);
        recordTask.setRemark(resultBody.toJSONString());
        if (StringUtils.isNotBlank(resultBody.getString("status")) && "200".equals(resultBody.getString("status"))) {
            JSONObject dataJson = resultBody.getJSONObject("data");
            recordTask.setPushStatus(TaskPushStatus.推送成功.status);
            recordTask.setTpCId(dataJson.getString("c_info_id"));

        }else{
            recordTask.setPushStatus(TaskPushStatus.推送失败.status);

        }
        recordTask.setPushTime(new Date());

    }

    @Override
    public void query(ClueTaskQueryLog queryLog) {
        log.info("XLBCarPlate 开始查询={}", JSON.toJSON(queryLog));
        String key = queryLog.getTpUsername();
        long time = System.currentTimeMillis() ;

        JSONArray cInfoIdList = new JSONArray();
        JSONObject cInfoId = new JSONObject();
        cInfoId.put("c_info_id", queryLog.getTpCId());
        cInfoIdList.add(cInfoId);
        String cInfoIdListStr = cInfoIdList.toJSONString();

        String sign = generateMD5Signature(String.format("%s%s%s", key, time, cInfoIdListStr));

        JSONObject bodyMap = new JSONObject();
        bodyMap.put("key", key);
        bodyMap.put("time", time);
        bodyMap.put("sign", sign);
        bodyMap.put("c_info_id_list", cInfoIdListStr);

        String requestUrl = PUSH_URL;
        HttpRequest request = HttpUtil.createPost(requestUrl);
        request.contentType("application/json");
        request.body(bodyMap.toJSONString());
        log.info("requestUrl {}", requestUrl);
        log.info("requestBody {}", bodyMap);
        HttpResponse execute = request.execute();
        String body = execute.body();
        log.info("XLBCarPlate 查询结果={}", body);

        JSONObject resultBody = JSONObject.parseObject(body);
        queryLog.setRemark(resultBody.toJSONString());
        if ("200".equals(resultBody.getString("status"))) {
            JSONObject data = resultBody.getJSONObject("data");

            String nodeName = Optional.ofNullable(data.getString("node_name")).orElse("");
            String nodeStatus = Optional.ofNullable(data.getString("node_status")).orElse("");
            // 已经处理
            if ("1".equals(nodeName)) {
                queryLog.setXlbHandleStatus(nodeStatus);
            }
            // 已经存储
            if ("2".equals(nodeName)) {
                queryLog.setXlbStoreStatus(nodeStatus);
            }

            // 已经建单
            if ("3".equals(nodeName)) {
                queryLog.setXlbBuildStatus(nodeStatus);
            }
        }else {
            queryLog.setQueryStatus(ClueQueryStatus.查询失败.status);
        }

    }
}
